package com.itboye.sunsun.luntan;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.os.Vibrator;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.itboye.sunsunhome.R;


/**
 * Created by fuweiwei on 2016/1/9.
 */
public class DragGridView extends GridView{
    /** 鐐瑰嚮鏃跺�欑殑X浣嶇疆 */
    public int downX;
    /** 鐐瑰嚮鏃跺�欑殑Y浣嶇疆 */
    public int downY;
    /** 鐐瑰嚮鏃跺�欏搴旀暣涓晫闈㈢殑X浣嶇疆 */
    public int windowX;
    /** 鐐瑰嚮鏃跺�欏搴旀暣涓晫闈㈢殑Y浣嶇疆 */
    public int windowY;
    /** VIEW鐩稿鑷繁鐨刋 */
    private int win_view_x;
    /**VIEW鐩稿鑷繁鐨刌*/
    private int win_view_y;
    /** 闀挎寜鏃跺�欏搴攑ostion */
    public int dragPosition;
    /** Up鍚庡搴旂殑ITEM鐨凱osition */
    private int dropPosition;
    /** 寮�濮嬫嫋鍔ㄧ殑ITEM鐨凱osition*/
    private int startPosition;
    /** item楂� */
    private int itemHeight;
    /** item瀹� */
    private int itemWidth;
    /** 鎷栧姩鐨勬椂鍊欏搴擨TEM鐨刅IEW */
    private View dragImageView = null;
    /** 闀挎寜鐨勬椂鍊橧TEM鐨刅IEW*/
    private ViewGroup dragItemView = null;
    /** WindowManager绠＄悊鍣� */
    private WindowManager windowManager = null;
    /** */
    private WindowManager.LayoutParams windowParams = null;
    /** item鎬婚噺*/
    private int itemTotalCount;
    /** 涓�琛岀殑ITEM鏁伴噺*/
    private int nColumns = 4;
    /** 琛屾暟 */
    private int nRows;
    /** 鍓╀綑閮ㄥ垎 */
    private int Remainder;
    /** 鏄惁鍦ㄧЩ鍔� */
    private boolean isMoving = false;
    /** */
    private int holdPosition;
    /** 鎷栧姩鐨勬椂鍊欐斁澶х殑鍊嶆暟 */
    private double dragScale = 1.2D;
    /** 闇囧姩鍣�  */
    private Vibrator mVibrator;
    /** 姣忎釜ITEM涔嬮棿鐨勬按骞抽棿璺� */
    private int mHorizontalSpacing = 15;
    /** 姣忎釜ITEM涔嬮棿鐨勭珫鐩撮棿璺� */
    private int mVerticalSpacing = 15;
    /** 绉诲姩鏃跺�欐渶鍚庝釜鍔ㄧ敾鐨処D */
    private String LastAnimationID;
    public DragGridView(Context context) {
        super(context);
        init(context);
    }

    public DragGridView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    public DragGridView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }
    /**
     * dip杞负 px
     */
    public  int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    public void init(Context context){
        mVibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
        //灏嗗竷灞�鏂囦欢涓缃殑闂磋窛dip杞负px
        mHorizontalSpacing = dip2px(context, mHorizontalSpacing);
    }
    /** 鍦⊿crollView鍐咃紝鎵�浠ヨ杩涜璁＄畻楂樺害 */
    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, expandSpec);
    }
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            downX = (int) ev.getX();
            downY = (int) ev.getY();
            windowX = (int) ev.getX();
            windowY = (int) ev.getY();
            setOnItemClickListener(ev);
        }
        return super.dispatchTouchEvent(ev);
    }
    /** 鍋滄鎷栧姩 锛岄噴鏀惧苟鍒濆鍖� */
    private void stopDrag() {
        if (dragImageView != null) {
            windowManager.removeView(dragImageView);
            dragImageView = null;
        }
    }

    /** 鍦ㄦ嫋鍔ㄧ殑鎯呭喌鏇存柊View鐨勪綅缃� */
    private void onDrag(int x, int y , int rawx , int rawy) {
        if (dragImageView != null) {
            windowParams.alpha = 0.6f;
            windowParams.x = rawx - win_view_x;
            windowParams.y = rawy - win_view_y;
            windowManager.updateViewLayout(dragImageView, windowParams);
        }
    }

    /**
     *鍒涘缓绐楀彛瀵硅薄銆佹坊鍔犳垜浠绉诲姩鐨刅iew
     * @param dragBitmap
     * @param x
     * @param y
     */
    public void startDrag(Bitmap dragBitmap, int x, int y) {
        stopDrag();
        windowParams = new WindowManager.LayoutParams();// 鑾峰彇WINDOW鐣岄潰鐨�
        //Gravity.TOP|Gravity.LEFT;杩欎釜蹇呴』鍔�
        windowParams.gravity = Gravity.TOP | Gravity.LEFT;
        //寰楀埌瑕佺Щ鍔ㄧ殑View宸︿笂瑙掔浉瀵逛簬灞忓箷鐨勫潗鏍�
        windowParams.x = x - win_view_x;
        windowParams.y = y  - win_view_y;
        //璁剧疆鎷栨嫿item鐨勫鍜岄珮
        windowParams.width = (int) (dragScale * dragBitmap.getWidth());// 鏀惧ぇdragScale鍊嶏紝鍙互璁剧疆鎷栧姩鍚庣殑鍊嶆暟
        windowParams.height = (int) (dragScale * dragBitmap.getHeight());// 鏀惧ぇdragScale鍊嶏紝鍙互璁剧疆鎷栧姩鍚庣殑鍊嶆暟
        this.windowParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
                | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
                | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
        this.windowParams.format = PixelFormat.TRANSLUCENT;
        this.windowParams.windowAnimations = 0;
        ImageView iv = new ImageView(getContext());
        iv.setImageBitmap(dragBitmap);
        windowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);// "window"
        windowManager.addView(iv, windowParams);
        dragImageView = iv;
    }
    /** 闅愯棌 鏀句笅 鐨処TEM*/
    private void hideDropItem() {
        ((DragAdapter) getAdapter()).setShowDropItem(false);
    }

    /** 鍦ㄦ澗鎵嬩笅鏀剧殑鎯呭喌锛屾洿鏂扮晫闈� */
    private void onDrop(int x, int y) {
        // 鏍规嵁鎷栧姩鍒扮殑x,y鍧愭爣鑾峰彇鎷栧姩浣嶇疆涓嬫柟鐨処TEM瀵瑰簲鐨凱OSTION
        int tempPostion = pointToPosition(x, y);
//		if (tempPostion != AdapterView.INVALID_POSITION) {
        dropPosition = tempPostion;
        DragAdapter mDragAdapter = (DragAdapter) getAdapter();
        //鏄剧ず鍒氭嫋鍔ㄧ殑ITEM
        mDragAdapter.setShowDropItem(true);
        //鍒锋柊閫傞厤鍣紝璁╁搴旂殑ITEM鏄剧ず
        mDragAdapter.notifyDataSetChanged();
//		}
    }
    /**
     * 闀挎寜鐐瑰嚮鐩戝惉
     * @param ev
     */
    public void setOnItemClickListener(final MotionEvent ev) {
        setOnItemLongClickListener(new OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                int x = (int) ev.getX();// 闀挎寜浜嬩欢鐨刋浣嶇疆
                int y = (int) ev.getY();// 闀挎寜浜嬩欢鐨剏浣嶇疆
                startPosition = position;// 绗竴娆＄偣鍑荤殑postion
                dragPosition = position;
                if (startPosition <= 1) {//鍓�2涓粯璁や笉鐐瑰嚮銆佸彲浠ヨ缃�
                    return false;
                }
                ViewGroup dragViewGroup = (ViewGroup) getChildAt(dragPosition - getFirstVisiblePosition());
                TextView dragTextView = (TextView)dragViewGroup.findViewById(R.id.text_item);
                dragTextView.setSelected(true);
                dragTextView.setEnabled(false);
                itemHeight = dragViewGroup.getHeight();
                itemWidth = dragViewGroup.getWidth();
                itemTotalCount = DragGridView.this.getCount();
                // 濡傛灉鐗规畩鐨勮繖涓笉绛変簬鎷栧姩鐨勯偅涓�,骞朵笖涓嶇瓑浜�-1
                if (dragPosition != AdapterView.INVALID_POSITION) {
                    // 閲婃斁鐨勮祫婧愪娇鐢ㄧ殑缁樺浘缂撳瓨銆傚鏋滀綘璋冪敤buildDrawingCache()鎵嬪姩娌℃湁璋冪敤setDrawingCacheEnabled(鐪熸鐨�),浣犲簲璇ユ竻鐞嗙紦瀛樹娇鐢ㄨ繖绉嶆柟娉曘��
                    win_view_x = windowX - dragViewGroup.getLeft();//VIEW鐩稿鑷繁鐨刋锛屽崐鏂�
                    win_view_y = windowY - dragViewGroup.getTop();//VIEW鐩稿鑷繁鐨剏锛屽崐鏂�
                    dragItemView = dragViewGroup;
                    dragViewGroup.destroyDrawingCache();
                    dragViewGroup.setDrawingCacheEnabled(true);
                    Bitmap dragBitmap = Bitmap.createBitmap(dragViewGroup.getDrawingCache());
                    mVibrator.vibrate(50);//璁剧疆闇囧姩鏃堕棿
                    startDrag(dragBitmap, (int)ev.getRawX(),  (int)ev.getRawY());
                    hideDropItem();
                    dragViewGroup.setVisibility(View.INVISIBLE);
                    isMoving = false;
                    return true;
                }
                return false;
            }
        });
    }
    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        if (dragImageView != null && dragPosition != AdapterView.INVALID_POSITION) {
            // 绉诲姩鏃跺�欑殑瀵瑰簲x,y浣嶇疆
            int x = (int) ev.getX();
            int y = (int) ev.getY();
            switch (ev.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    downX = (int) ev.getX();
                    windowX = (int) ev.getX();
                    downY = (int) ev.getY();
                    windowY = (int) ev.getY();
                    break;
                case MotionEvent.ACTION_MOVE:
                    onDrag(x, y ,(int) ev.getRawX() , (int) ev.getRawY());
                    if (!isMoving){
                        OnMove(x, y);
                    }
                    if (pointToPosition(x, y) != AdapterView.INVALID_POSITION){
                        break;
                    }
                    break;
                case MotionEvent.ACTION_UP:
                    stopDrag();
                    onDrop(x, y);
                    requestDisallowInterceptTouchEvent(false);
                    break;

                default:
                    break;
            }
        }
        return super.onTouchEvent(ev);
    }
    /** 绉诲姩鐨勬椂鍊欒Е鍙戯紝绉诲姩鎵�鏈夋敼鍙樼殑Item*/
    public void OnMove(int x, int y) {
        // 鎷栧姩鐨刅IEW涓嬫柟鐨凱OSTION
        int dPosition = pointToPosition(x, y);
        // 鍒ゆ柇涓嬫柟鐨凱OSTION鏄惁鏄渶寮�濮�2涓笉鑳芥嫋鍔ㄧ殑
        if (dPosition > 1) {
            if ((dPosition == -1) || (dPosition == dragPosition)){
                return;
            }
            dropPosition = dPosition;
            if (dragPosition != startPosition){
                dragPosition = startPosition;
            }
            int movecount;
            //鎷栧姩鐨�=寮�濮嬫嫋鐨勶紝骞朵笖 鎷栧姩鐨� 涓嶇瓑浜庢斁涓嬬殑
            if ((dragPosition == startPosition) || (dragPosition != dropPosition)){
                //绉婚渶瑕佺Щ鍔ㄧ殑鍔↖TEM鏁伴噺
                movecount = dropPosition - dragPosition;
            }else{
                //绉婚渶瑕佺Щ鍔ㄧ殑鍔↖TEM鏁伴噺涓�0
                movecount = 0;
            }
            if(movecount == 0){
                return;
            }
            int movecount_abs = Math.abs(movecount);
            if (dPosition != dragPosition) {
                //dragGroup璁剧疆涓轰笉鍙
                ViewGroup dragGroup = (ViewGroup) getChildAt(dragPosition);
                dragGroup.setVisibility(View.INVISIBLE);
                float to_x = 1;//绉诲姩鐨刋鍋忕Щ閲�
                float to_y;// 绉诲姩鐨刌鍋忕Щ閲�
                //x_vlaue绉诲姩鐨勮窛绂荤櫨鍒嗘瘮锛堢浉瀵逛簬鑷繁闀垮害鐨勭櫨鍒嗘瘮锛�
                float x_vlaue = ((float) mHorizontalSpacing / (float) itemWidth) + 1.0f;
                //y_vlaue绉诲姩鐨勮窛绂荤櫨鍒嗘瘮锛堢浉瀵逛簬鑷繁瀹藉害鐨勭櫨鍒嗘瘮锛�
                float y_vlaue = ((float) mVerticalSpacing / (float) itemHeight) + 1.0f;
                Log.d("x_vlaue", "x_vlaue = " + x_vlaue);
                for (int i = 0; i < movecount_abs; i++) {
                    to_x = x_vlaue;
                    to_y = y_vlaue;
                    //鍚戝彸
                    if (movecount > 0) {
                        // 鍒ゆ柇鏄笉鏄悓涓�琛岀殑
                        holdPosition = dragPosition + i + 1;
                        if (dragPosition / nColumns == holdPosition / nColumns) {
                            to_x = - x_vlaue;
                            to_y = 0;
                        } else if (holdPosition % 4 == 0) {
                            to_x = 3 * x_vlaue;
                            to_y = - y_vlaue;
                        } else {
                            to_x = - x_vlaue;
                            to_y = 0;
                        }
                    }else{
                        //鍚戝乏,涓嬬Щ鍒颁笂锛屽彸绉诲埌宸�
                        holdPosition = dragPosition - i - 1;
                        if (dragPosition / nColumns == holdPosition / nColumns) {
                            to_x = x_vlaue;
                            to_y = 0;
                        } else if((holdPosition + 1) % 4 == 0){
                            to_x = -3 * x_vlaue;
                            to_y = y_vlaue;
                        }else{
                            to_x = x_vlaue;
                            to_y = 0;
                        }
                    }
                    ViewGroup moveViewGroup = (ViewGroup) getChildAt(holdPosition);
                    Animation moveAnimation = getMoveAnimation(to_x, to_y);
                    moveViewGroup.startAnimation(moveAnimation);
                    //濡傛灉鏄渶鍚庝竴涓Щ鍔ㄧ殑锛岄偅涔堣缃粬鐨勬渶鍚庝釜鍔ㄧ敾ID涓篖astAnimationID
                    if (holdPosition == dropPosition) {
                        LastAnimationID = moveAnimation.toString();
                    }
                    moveAnimation.setAnimationListener(new Animation.AnimationListener() {

                        @Override
                        public void onAnimationStart(Animation animation) {
                            isMoving = true;
                        }

                        @Override
                        public void onAnimationRepeat(Animation animation) {

                        }

                        @Override
                        public void onAnimationEnd(Animation animation) {
                            // 濡傛灉涓烘渶鍚庝釜鍔ㄧ敾缁撴潫锛岄偅鎵ц涓嬮潰鐨勬柟娉�
                            if (animation.toString().equalsIgnoreCase(LastAnimationID)) {
                                DragAdapter mDragAdapter = (DragAdapter) getAdapter();
                                mDragAdapter.exchange(startPosition,dropPosition);
                                startPosition = dropPosition;
                                dragPosition = dropPosition;
                                isMoving = false;
                            }
                        }
                    });
                }
            }
        }
    }
    /** 鑾峰彇绉诲姩鐨勫姩鐢� */
    public Animation getMoveAnimation(float toXValue, float toYValue) {
        TranslateAnimation mTranslateAnimation = new TranslateAnimation(
                Animation.RELATIVE_TO_SELF, 0.0F,
                Animation.RELATIVE_TO_SELF,toXValue,
                Animation.RELATIVE_TO_SELF, 0.0F,
                Animation.RELATIVE_TO_SELF, toYValue);// 褰撳墠浣嶇疆绉诲姩鍒版寚瀹氫綅缃�
        mTranslateAnimation.setFillAfter(true);// 璁剧疆涓�涓姩鐢绘晥鏋滄墽琛屽畬姣曞悗锛孷iew瀵硅薄淇濈暀鍦ㄧ粓姝㈢殑浣嶇疆銆�
        mTranslateAnimation.setDuration(300L);
        return mTranslateAnimation;
    }
}
